import logging

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class CeleryTaskSequence(models.Model):
    """Celery任务序列
    """
    _name = 'celery.task.sequence'
    _description = 'Celery任务序列'
    _order = 'create_time desc'

    name = fields.Char(
        string='序列编号',
        default=lambda self: self.env['ir.sequence'].next_by_code('celery.task.sequence')
    )
    create_time = fields.Datetime(string='创建时间', default=fields.Datetime.now)
    task_ids = fields.One2many(comodel_name='celery.task', inverse_name='sequence_id', string='任务序列')
    sequence_type = fields.Selection(
        string='序列类型',
        selection=[
            ('collection_update', '合集更新'),
            ('collection_reload', '合集重载'),
            ('create_collection', '创建合集'),
            ('collection_merge', '合集合并'),
            ('collection_manual_update', '手动更新合集'),
            ('create_fake_collection', '创建伪合集'),
            ('publish_update', '发布更新')
        ]
    )
    status = fields.Selection(
        string='序列状态',
        selection=[
            ('draft', '未开始'),
            ('ongoing', '执行中'),
            ('finish', '已完成'),
            ('partial', '部分完成'),
            ('error', '错误')
        ],
        compute='_compute_status'
    )

    def action_run_sequence(self):
        '''所有的任务都通过该API网关执行'''
        self.mapped('task_ids').filtered(lambda r: r.status != 'finish').action_run_task()

    def action_sequence_rerun(self):
        self.task_ids.action_task_rerun()

    @api.depends('task_ids', 'task_ids.status')
    def _compute_status(self):
        for rec in self:
            all_task_status = rec.task_ids.mapped('status')
            if 'error' in all_task_status:
                status = 'error'
            elif all(map(lambda status: status == 'finish', all_task_status)):
                status = 'finish'
            elif 'finish' in all_task_status:
                # 部分完成的状态可能包含正在执行的任务
                status = 'partial'
            elif 'ongoing' in all_task_status:
                status = 'ongoing'
            else:
                status = 'draft'
            rec.status = status